{% extends 'common_project_tpl.html' %}
{% load static %}
{% block css %}
    <link rel="stylesheet" href="{% static 'plugins/editor-md/css/editormd.min.css' %}">
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-datepicker/css/bootstrap-datepicker.min.css' %}">
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-select/css/bootstrap-select.min.css' %}">
    <link rel="stylesheet" href="{% static 'plugins/select2/css/select2.min.css' %}">
    <style>
        .issues-list .number {
            width: 100px;
            text-align: right;
        }

        .issues-list .number a {
            font-weight: 500;
            padding: 0 10px;
        }

        .issues-list .issue .tags {
            padding: 10px 0;
        }

        .issues-list .issue .tags span {
            margin-right: 20px;
            display: inline-block;
            font-size: 12px;
        }

        .issues-list .issue .tags .type {
            color: white;
            padding: 1px 5px;
            border-radius: 5px;
            background-color: #dddddd;
        }

        .editormd-fullscreen {
            z-index: 1001;
        }

        .error-msg {
            position: static;
        }

        .popover {
            width: 300px;
        }
    </style>
{% endblock %}
{% block content %}
    <div class="container-fluid clearfix" style="padding: 20px 0;">
        <div class="col-sm-3">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <i class="fa fa-search" aria-hidden="true"></i> 筛选
                </div>
                <div class="panel-body filter-area">
                    <form id="search-form">
                        {% for choice in choices %}
                            <div class="form-group">
                                <div style="font-weight: bold;margin: 5px 0;" class="bg-info">{{ choice.title }}</div>
                                {% for items in choice.data_iter %}
                                    <label class="checkbox-inline">
                                        <input name="{{ choice.name }}" type="checkbox"
                                               value="{{ items.value }}" {{ items.mark }}> {{ items.name }}
                                    </label>
                                {% endfor %}
                            </div>
                        {% endfor %}
                        {% for select in selects %}
                            <div class="form-group">
                                <div style="font-weight: bold;margin: 5px 0;" class="bg-info">{{ select.title }}</div>
                                <select multiple class="form-control select2" name="{{ select.name }}">
                                    {% for items in select.data_iter %}
                                        <option value="{{ items.value }}" {{ items.mark }}>{{ items.name }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        {% endfor %}
                        <button id="search" type="button" class="btn btn-primary btn-sm">搜索</button>
                    </form>
                </div>
            </div>
        </div>
        <div class="col-sm-9">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <i class="fa fa-quora" aria-hidden="true"></i> 问题
                </div>
                <div class="panel-body">
                    <div>
                        <a class="btn btn-success btn-sm" data-toggle="modal" data-target="#addIssue">新建问题
                        </a>
                        <a class="btn btn-primary btn-sm" data-toggle="modal" data-target="#invite">邀请成员</a>
                    </div>
                </div>
                <table class="table">
                    <tbody class="issues-list">
                    <tr class="hide">
                        <td class="number">
                            <i class="fa fa-circle" style="color: red"></i>
                            <a>#010</a>
                        </td>
                        <td class="issue">
                            <div>
                                <a href="#">这是项目标题</a>
                            </div>
                            <div class="tags">
                                <span class='label label-success type'>功能</span>
                                <span><i class="fa fa-refresh" aria-hidden="true"></i>
                                        公开
                                    </span>
                                <span>
                                        <i class="fa fa-hand-o-right" aria-hidden="true"></i>
                                        指派人
                                    </span>
                                <span>
                                        <i class="fa fa-user-o" aria-hidden="true"></i>
                                        创建人
                                    </span>
                                <span><i class="fa fa-calendar" aria-hidden="true"></i>
                                        2023年11月2日 13:50 截止
                                    </span>
                                <span><i class="fa fa-clock-o" aria-hidden="true"></i>
                                        2023年11月2日 13:50 更新
                                    </span>
                            </div>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
            <div class="bs-example" data-example-id="disabled-active-pagination">
                <nav aria-label="adfasdf">
                    <ul class="pagination">
                        <li>
                            <a href="#" id="first-page"><span aria-hidden="true">首页</span></a>
                        </li>
                        <li>
                            <a href="#" aria-label="Previous"><span aria-hidden="true">«</span></a>
                        </li>
                        <li id="page-start"><a href="#" aria-label="Next"><span aria-hidden="true">»</span></a></li>
                        <li>
                            <a href="#" id="last-page"><span aria-hidden="true">尾页</span></a>
                        </li>
                        <li class="disabled">
                            <a href="#" id="page-location"><span aria-hidden="true"></span></a>
                        </li>
                    </ul>
                </nav>
            </div>
        </div>
    </div>
    <!-- Modal -->
    <div class="modal fade" id="addIssue" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">新建问题</h4>
                </div>
                <div class="modal-body" style="padding-right: 40px;">
                    <form id="issue-form" class="form-horizontal">
                        {% csrf_token %}
                        <div class="form-group">
                            <label for="{{ form.issues_type.id_for_label }}"
                                   class="col-md-2 control-label">{{ form.issues_type.label }}</label>
                            <div class="col-md-10">
                                <div>
                                    <div>
                                        {{ form.issues_type }}
                                        <div class="error-msg"></div>
                                    </div>
                                </div>
                                <div class="error-msg"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="{{ form.subject.id_for_label }}"
                                   class="col-md-2 control-label">{{ form.subject.label }}</label>
                            <div class="col-md-10">
                                <div>
                                    <div>
                                        {{ form.subject }}
                                    </div>
                                    <div class="error-msg"></div>
                                </div>
                                <div class="error-msg"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="{{ form.module.id_for_label }}"
                                   class="col-md-2 control-label">{{ form.module.label }}</label>
                            <div class="col-md-10">
                                <div>
                                    <div>
                                        {{ form.module }}
                                    </div>
                                    <div class="error-msg"></div>
                                </div>
                                <div class="error-msg"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="{{ form.desc.id_for_label }}"
                                   class="col-md-2 control-label">{{ form.desc.label }}</label>
                            <div class="col-md-10">
                                <div>
                                    <div id="editor">
                                        {{ form.desc }}
                                    </div>

                                    <div class="error-msg"></div>
                                </div>
                                <div class="error-msg"></div>
                            </div>
                        </div>

                        <div class="form-group clearfix">

                            <div class="col-md-6 pd-0">
                                <label for="{{ form.status.id_for_label }}"
                                       class="col-md-4 control-label">{{ form.status.label }}</label>
                                <div class="col-md-8 clearfix">
                                    <div>
                                        {{ form.status }}
                                    </div>
                                    <div class="error-msg"></div>

                                </div>
                            </div>
                            <div class="col-md-6 pd-0">
                                <label for=" {{ form.priority.id_for_label }}"
                                       class="col-md-4 control-label">{{ form.priority.label }}</label>
                                <div class="col-md-8">
                                    <div>
                                        {{ form.priority }}
                                    </div>
                                    <div class="error-msg"></div>

                                </div>
                            </div>
                        </div>

                        <div class="form-group clearfix">
                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">指派给</label>
                                <div class="col-md-8">
                                    {{ form.assign }}
                                    <div class="error-msg"></div>
                                </div>
                            </div>

                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">关注者</label>
                                <div class="col-md-8">

                                    {{ form.attention }}

                                    <div class="error-msg"></div>
                                </div>
                            </div>
                        </div>

                        <div class="form-group clearfix">
                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">开始时间</label>
                                <div class="col-md-8">

                                    <div class="input-group">
                                        <span class="input-group-addon" id="sizing-addon2">
                                            <i class="fa fa-calendar" aria-hidden="true"></i>
                                        </span>
                                        {{ form.start_date }}
                                    </div>
                                    <span class="error-msg"></span>

                                </div>
                            </div>

                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">截止时间</label>
                                <div class="col-md-8">

                                    <div class="input-group">
                                        <span class="input-group-addon" id="sizing-addon2">
                                            <i class="fa fa-calendar" aria-hidden="true"></i>
                                        </span>
                                        {{ form.end_date }}
                                    </div>
                                    <span class="error-msg"></span>
                                </div>
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">模式</label>
                                <div class="col-md-8">
                                    <div>
                                        {{ form.mode }}
                                    </div>
                                    <div class="error-msg"></div>
                                </div>
                            </div>

                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label"> 父问题</label>
                                <div class="col-md-8">

                                    {{ form.parent }}

                                    <div class="error-msg"></div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消
                    </button>
                    <button id="create_issue" type="button" class="btn btn-primary">新建</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal -->
    <div class="modal fade" id="errorModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title label-warning" id="myModalLabel"><i class="fa fa-warning"
                                                                               aria-hidden="true"></i>错误</h4>
                </div>
                <div class="modal-body">
                    <div class="error-msg">
                        数据获取失败！
                        <div id="error-list"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal -->
    <div class="modal fade" id="invite" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel"><i class="fa fa-id-card" aria-hidden="true"></i> 生成邀请码
                    </h4>
                </div>
                <div class="modal-body">
                    <form id="invite-form">
                        {% csrf_token %}
                        {% for field in invite_form %}
                            <div class="form-group">
                                <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                                <span>{% if  field.help_text %}（{{ field.help_text }}）{% endif %}</span>
                                {{ field }}
                                <span class="error-msg"></span>
                            </div>
                        {% endfor %}
                        <button id="create_invite_code" type="button" class="btn btn-success">生成邀请码</button>
                    </form>
                </div>
                <div id="invite_code_show" class="hide">
                    <hr>
                    <div class="input-group" style="padding: 15px">
                        <span class="input-group-addon">邀请链接</span>
                        <input type="text" class="form-control" id="code"
                               aria-describedby="inputGroupSuccess1Status">
                        <div class="input-group-btn">
                            <a class="btn btn-primary" id="copy_code" role="button" tabindex="0" data-toggle="popover"
                               data-trigger="focus" title="复制成功" data-content="请访问此网址，将会自动进入项目！">复制链接</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block js %}
    <script src="{% static 'plugins/editor-md/editormd.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-select/js/bootstrap-select.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-select/js/i18n/defaults-zh_CN.min.js' %}"></script>
    <script src="{% static 'plugins/select2/js/select2.min.js' %}"></script>
    <script src="{% static 'plugins/select2/js/i18n/zh-CN.js' %}"></script>
    <script>
        $(function () {
            initModal();
            initDatePicker();
            createIssue();
            getIssueList();
            getSearchData();
            initSelect2();
            getInviteCode();
            copyCode();
            $('[data-toggle="popover"]').popover();
        })

        function initSelect2() {
            $('.select2').select2();
        }

        function initModal() {
            $('#addIssue').on('shown.bs.modal', function (event) { // 当模态框显示时，会自动触发此函数
                initEditorMd();
            })
        }

        function initEditorMd() {
            editormd('editor', {
                placeholder: "请输入问题描述",
                height: 300,
                path: "{% static 'plugins/editor-md/lib/' %}",
                // 上传图片的开关
                imageUpload: true,
                // 上传图片允许格式
                imageFormats: ["jpg", 'jpeg', 'png', 'gif'],
                // 上传图片的接口，会自动向该接口发送post请求，已经在组件中封装好了
                imageUploadURL: "{% url 'main:api_wiki_upload' project=pro_id %}" + '?project=' +{{ pro_id }},
                flowChart: true,
                emoji: true,
            })
        }

        function initDatePicker() {

            $('#id_start_date,#id_end_date').datepicker({
                format: 'yyyy-mm-dd', // 显示的数据格式
                startDate: '0', // 表示从今天开始选择
                language: "zh-CN",
                autoclose: true
            });
        }

        function createIssue() {
            $("#create_issue").click(function () {
                $('.error-msg').empty();
                let data = {};
                $.each($('#issue-form').serializeArray(), function () {
                    data[this.name] = this.value;
                });
                data.project ={{ pro_id }};
                data.creator = {{ request.user.id }}
                    $.ajax({
                        url: "{% url 'main:issue-list' %}",
                        data: data,
                        dataType: 'json',
                        type: 'post',
                        success: function (res) {
                            if (res.ret === 0) {
                                location.reload();
                            } else {
                                $.each(res.errors, function (key, value) {
                                    $("#id_" + key).parent().next(".error-msg").text(value[0]);
                                })
                            }
                        }

                    })
            })

        }

        function getIssueList(url = "{% url 'main:issue-list' %}") {
            {#$(".issues-list").empty();#}
            {#$(".pagination").find('li.auto-add').remove();#}
            $.ajax({
                url: url + location.search,
                type: 'get',
                data: {
                    project:{{ pro_id }},
                    {% if pagenum %}
                        pagenum:{{ pagenum }}
                    {% endif %}
                },
                dataType: 'json',
                success: function (res) {
                    if (res.ret === 0) {
                        $.each(res.data, function (index, item) {
                            let COLOR = {
                                danger: 'red',
                                warning: 'orange',
                                success: 'green'
                            }
                            let detai_url = "{% url 'main:issues_detail' pro_id 1%}".replace('/detail/1', `/detail/${item.id}`)
                            let htmlCode = `
                            <tr>
                                <td class="number">
                                    <i class="fa fa-circle" style="color: ${COLOR[item.priority]}"></i>
                                    <a target="_blank" href=${detai_url}>#${addZero(item.id, 3)}</a>
                                </td>
                                <td class="issue">
                                    <div>
                                        <a target="_blank" href=${detai_url}>${item.subject}</a>
                                    </div>
                                    <div class="tags">
                                        <span class='label label-info'>${item.issues_type}</span>
                                        <span><i class="fa fa-refresh" aria-hidden="true"></i>
                                                ${item.status}
                                            </span>
                                        <span>
                                                <i class="fa fa-hand-o-right" aria-hidden="true"></i>
                                                ${item.assign}
                                            </span>
                                        <span>
                                                <i class="fa fa-user-o" aria-hidden="true"></i>
                                                ${item.creator}
                                            </span>
                                        <span><i class="fa fa-calendar" aria-hidden="true"></i>
                                                ${item.end_date} 截止
                                            </span>
                                        <span><i class="fa fa-clock-o" aria-hidden="true"></i>
                                                ${item.latest_update_datetime} 更新
                                            </span>
                                    </div>
                                </td>
                            </tr>
                            `
                            $(".issues-list").append(htmlCode)
                        })
                        pagination(res);

                    }
                },
                error: function (res) {
                    $('.pagination').addClass('hide')
                    let msg_list = [];
                    $.each(res.responseJSON, function (key, msg) {
                        msg_list.push(key + msg);
                    })
                    $('#error-list').text(msg_list.join('\n'));
                    $('#errorModal').modal();
                }
            })
        }

        function addZero(num, length) {
            for (let len = (num + "").length; len < length; len = num.length) {
                num = "0" + num;
            }
            return num;
        }

        function pagination(res) {
            if (res.page) {
                for (let i = res.page.current_page - 5 < 1 ? 1 : res.page.current_page - 5;
                     i <= res.page.page_count && i <= res.page.current_page + 5;
                     i++) {
                    if (i === res.page.current_page) {
                        var htmlCode = `<li class="active auto-add"><a href="{% url 'main:issues' pro_id%}${location.search}&pagenum=${i}">${i}</a></li>`
                    } else {
                        htmlCode = `<li class="auto-add"><a href="{% url 'main:issues' pro_id%}${location.search}&pagenum=${i}">${i}</a></li>`
                    }
                    $('#page-start').before(htmlCode)
                }
                let pre = $('[aria-label="Previous"]');
                let next = $('[aria-label="Next"]');
                if (res.page.previous) {
                    pre.attr('href', `{% url 'main:issues' pro_id%}${location.search}&pagenum=${res.page.current_page - 1}`);
                } else {
                    pre.parent().addClass("disabled");
                }
                ;
                if (res.page.next) {
                    next.attr('href', `{% url 'main:issues' pro_id%}${location.search}&pagenum=${res.page.current_page + 1}`)
                } else {
                    next.parent().addClass("disabled");
                }
                $('#first-page').attr('href', `{% url 'main:issues' pro_id%}${location.search}&pagenum=1`);
                $('#last-page').attr('href', `{% url 'main:issues' pro_id%}${location.search}&pagenum=${res.page.page_count}`);
                $('#page-location').text(res.page.page_location);
            }
        }

        function getSearchData() {
            $('#search').click(function () {
                let params = $('#search-form').serializeArray();
                console.log(params);
                let priority = [];
                let status = [];
                let issues_type = [];
                let assign = [];
                let other = [];
                $.each(params, function () {
                    if (this.name === 'priority__in') {
                        priority.push(this.value)
                    } else if (this.name === 'status__in') {
                        status.push(this.value)
                    } else if (this.name === 'issues_type__in') {
                        issues_type.push(this.value)
                    } else if (this.name === 'assign__in') {
                        assign.push(this.value)
                    } else {
                        other.push(this.name + "=" + this.value)
                    }
                })
                let url_params = "?" + 'priority__in=' + priority.join(',') + '&status__in=' + status.join(',') +
                    '&issues_type__in=' + issues_type.join(',') + "&assign__in=" + assign.join(',') + "&" + other.join("&");
                location.href = "{% url 'main:issues' pro_id %}" + url_params;
            })
        }

        function getInviteCode() {
            $('#create_invite_code').click(function () {
                $(".error-msg").empty();
                let data = {};
                let form_data = $('#invite-form').serializeArray();
                $.each(form_data, function () {
                    data[this.name] = this.value
                })
                data.project = {{ pro_id }}
                    $.ajax({
                        url: "{% url 'main:invite-list' %}",
                        data: data,
                        dataType: 'json',
                        type: "post",
                        success: function (res) {
                            if (res.ret === 0) {
                                $('#invite_code_show').removeClass('hide')
                                $('#code').val(res.link)
                                console.log(res)

                            } else {
                                $.each(res.errors, function (k, v) {
                                    $("#id_" + k).next().text(v)
                                })
                            }
                        }
                    })
            })
        }

        function copyCode() {
            $("#copy_code").click(function () {
                {#let textInput = $('#code')[0];#}
                {#textInput.select();#}
                {#document.execCommand()#}
                let value = $('#code').val();
                navigator.clipboard.writeText(value).then(() => {
                    $('#invite_code_show').find('.input-group').addClass('has-success');
                });

            })
        }
    </script>
{% endblock %}